package com.youpai.platform.vulture.service.handler.netty;

import com.alibaba.fastjson.JSONObject;
import com.youpai.platform.vulture.common.entity.AccessMessage;
import com.youpai.platform.vulture.service.channel.VultureChannel;
import com.youpai.platform.vulture.service.handler.vulture.IVultureChannelHandler;
import com.youpai.platform.vulture.service.support.VultureChannelSupport;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;


/**
 * @date: 2022/6/23 15:03
 * @author: Anna
 * @version: 1.0
 * @description: netty入口
 */
@Slf4j
@ChannelHandler.Sharable
public class NettyChannelHandler extends ChannelDuplexHandler {

    private final IVultureChannelHandler vultureChannelHandler;

    public NettyChannelHandler(IVultureChannelHandler vultureChannelHandler) {
        this.vultureChannelHandler = vultureChannelHandler;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        VultureChannel vultureChannel = VultureChannelSupport.getOrAddVultureChannel(ctx.channel());
        vultureChannelHandler.connect(vultureChannel);
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        VultureChannel vultureChannel = VultureChannelSupport.getVultureChannel(ctx.channel());
        vultureChannelHandler.disConnect(vultureChannel);
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        VultureChannel vultureChannel = VultureChannelSupport.getOrAddVultureChannel(ctx.channel());
        vultureChannelHandler.receive(vultureChannel, (AccessMessage) msg);
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        VultureChannel vultureChannel = VultureChannelSupport.getVultureChannel(ctx.channel());
        vultureChannelHandler.disConnect(vultureChannel);
        super.close(ctx, promise);
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        VultureChannel vultureChannel = VultureChannelSupport.getVultureChannel(ctx.channel());
        vultureChannelHandler.disConnect(vultureChannel);
        super.disconnect(ctx, promise);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("---error---{}", JSONObject.toJSONString(cause));
    }
}
